package org.shan.security.core.social.ali.config;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;

/**
 * Created by amanda.shan on 2019/3/20.
 */
public class AliUtils {

    public static String RSA_PUBLIC =
            "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApTHdlDMkG797yeEWZLUhxmjlZfEQei8Gp8B0V4GgoUNXS8YIWM" +
                    "/kZUnSFBQMYCp3b4GCetq82Hqr/NMCj/ok10nycEpe5" +
                    "+MfXadvdCaoCrtOPdma9PoC3jFLB8J88swjY3uyiHqAvCj5fCpMWP70wFsveWawvvsJMlyr28OvdbZ5R4JHZap89Oc/n6RB" +
                    "+E8jAHuCAOjJrVnsdZhtHSCXPRp0qPgxNh8JihY4+kdZpHEoUk+Gq2Pjc1AaE72qZyaKvLXdaiUDcvhcIXIBPHFrGtnWI" +
                    "/SHzNXUaxX4zQi/9uVcAqUtAMacHCJQyqxGl7BslGCkVRrfP907sceIbbpGCQIDAQAB";
    public static String
            RSA_PRIVATE = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC" +
            "+WBQTFjVlzQh7etLjYSb1LytbzamCCYlAU6uEzC0NqOUATElycqvZW/tqx/w8ufBfJSZBKoTARi5bnGPugfYenSb96Z" +
            "/Z3c3yJx4URqStn/HKOwb3vkxGU4dHMHvRSbOe1x5E+QamToaMCmcul/v//xrJilySy8tMOHUMUpidsC3V8vIOii1Y5+ngt4cniIqeR4" +
            "/UG5fDiKRZvLxCjHRp2eOmSA1r" +
            "/gvipBKedIeBVFPOoCArraKEpdSaGRF0jPRmv3dcg3FWU8p2p8gjiNwyCpX2y91Q66z9dbAFpZ0ZQY6Zj7ZDMTI8Fd68b" +
            "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XCUzCpjAoGBAMZSx35UkCCIYTNELwkr3ihFiMNuSrgPT3Ww0FKyY3GIJIjioLVdIN+9kq5R9XyhKubY2LXPhQOjiCol0yd5AzX+UdGiR18ytNkCj9i/m6xuX8zR8yWRH4DYKGV1QkLdtNSvl1I2YCH1iUoh/XC8TEisX9pAzr1oH/KILVLSVgkb";

    private static AlipayClient alipayClient;

    public static void init(String appId) {
        alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                appId,
                AliUtils.RSA_PRIVATE, "json", "GBK", AliUtils.RSA_PUBLIC, "RSA2");

    }

    public static AlipaySystemOauthTokenResponse getToken(String code) throws AlipayApiException {
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setGrantType("authorization_code");
        request.setCode(code);
        AlipaySystemOauthTokenResponse response = null;

        response = alipayClient.execute(request);

        if (response.isSuccess()) {
            return response;
        } else {
            throw new RuntimeException("获取支付宝token失败");

        }

    }

    public static AlipayUserInfoShareResponse getUserInfoByToken() throws AlipayApiException {
        AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest();
        String auth_token = "authbseB2b4ca144ff80437f93c9e4ff9b97bX18";
        return alipayClient.execute(request, auth_token);
    }

}
